package com.xueyi.workflow.listener;

import com.xueyi.workflow.event.ProcessCompletedEvent;
import com.xueyi.workflow.service.IWfProcessInstanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 流程完成事件监听器
 * 监听流程完成事件，并更新业务表状态
 *
 * @author xueyi
 * @date 2024-08-26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProcessCompletedEventListener {
    
    private final IWfProcessInstanceService wfProcessInstanceService;
    
    /**
     * 监听流程完成事件
     */
    @EventListener
    @Async
    public void handleProcessCompleted(ProcessCompletedEvent event) {
        try {
            String processInstanceId = event.getProcessInstanceId();
            String businessKey = event.getBusinessKey();
            String processDefinitionKey = event.getProcessDefinitionKey();
            
            log.info("收到流程完成事件，processInstanceId: {}, businessKey: {}, processDefinitionKey: {}", 
                    processInstanceId, businessKey, processDefinitionKey);
            
            // 更新流程实例状态为已完成
            boolean success = wfProcessInstanceService.updateStatusToCompleted(processInstanceId);
            
            if (success) {
                log.info("流程实例 {} 状态更新成功，已标记为 COMPLETED", processInstanceId);
            } else {
                log.warn("流程实例 {} 状态更新失败", processInstanceId);
            }
            
        } catch (Exception e) {
            log.error("处理流程完成事件失败", e);
        }
    }
}
